package com.woniu.controller;

/**
 * @author 李桢
 * @time 2021/03/31 09:41:29
 */

import com.woniu.serivce.UserInfosService;
import com.woniu.util.JwtCreatUtils;
import com.woniu.util.JwtVerifyGetUserNameUtils;
import com.woniu.util.ResultVO;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

/**
 * @author 李桢
 * @time 2021/03/31 09:55:09
 */
@RestController
public class AuthController {

    @Qualifier("redisTemplate")
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserInfosService userService;

    @GetMapping("/auth/test")
    public ResultVO test() {
        return ResultVO.success("test...");
    }

    @GetMapping("/auth/login/{userName}/{userPsw}")
    public ResultVO login(@PathVariable() String userName, @PathVariable() String userPsw) {

        //判断账号密码是否正确
        ResultVO resultVO = userService.findUser(userName,userPsw);

        if (resultVO.getCode() != 200) {
            ResultVO vo = new ResultVO(403,"Account or password error");
            return vo;
        }

        // 账号密码正确，生成token
        String token = JwtCreatUtils.createToken(userName, 3600);
        redisTemplate.opsForValue().set(userName,token,1, TimeUnit.MINUTES);
        return ResultVO.success(token);
    }

    @PostMapping("/auth/logout")
    public ResultVO logout(@RequestBody String token) {
        //从token信息中获取userName
        String username = JwtVerifyGetUserNameUtils.getUsername(token);
        //删除token
        Boolean b = redisTemplate.delete(username);
        if (b){
            return ResultVO.success();
        }
        return ResultVO.failure();
    }

}
